import React, {Component} from 'react'
import cx from 'classnames'
import { observer, inject } from 'mobx-react'

import { runInAction } from 'mobx'

import {Form, Input, Icon, Row, Col, message} from 'antd'
import styles from './Login.less'
import {randomNum} from 'utils/utils'
import BGParticle from 'utils/BGParticle'
import { login } from './LoginServ.js'
import Cookies from 'js-cookie'
import config from 'config/config.js'

const FormItem = Form.Item

@Form.create()
@inject('login')
@observer
class LoginView extends Component {
  constructor(props) {
    super(props)
    this.login = this.props.login
  }

  componentDidMount () {
    this.initPage()
    this.createCode()
  }

  componentWillUnmount() {
    this.particle.destory()
  }
 
  // 初始化页面
  initPage = () => {
    this.particle = new BGParticle('backgroundBox'),
    this.particle.init()
  }

  doLogin = () => {
    let that = this
    if(this.login.code !== this.login.CODE) {
      message.error('验证码错误')
      return
    }
    login({
      username: this.login.username,
      password: this.login.password
    }).then(function(res) {
      console.log(res.data.token)
      Cookies.set(config.cookie.token, res.data.token, { expires: 7 });
      Cookies.set(config.cookie.username, res.data.username, {expires: 7})
      message.success('登录成功')
      // 跳转路由
      
      that.props.history.push('/')
    })
  }

  // 生成验证码
  createCode = () => {
    const ctx = this.canvas.getContext('2d')
    const chars = [1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'j', 'k', 'l', 'm', 'n', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
    let code = ''
    ctx.clearRect(0, 0, 80, 39)
    for (let i = 0; i < 4; i++) {
      const char = chars[randomNum(0, 57)]
      code += char
      ctx.font = randomNum(20, 25) + 'px SimHei'  //设置字体随机大小
      ctx.fillStyle = '#D3D7F7'
      ctx.textBaseline = 'middle'
      ctx.shadowOffsetX = randomNum(-3, 3)
      ctx.shadowOffsetY = randomNum(-3, 3)
      ctx.shadowBlur = randomNum(-3, 3)
      ctx.shadowColor = 'rgba(0, 0, 0, 0.3)'
      let x = 80 / 5 * (i + 1)
      let y = 39 / 2
      let deg = randomNum(-25, 25)
      /**设置旋转角度和坐标原点**/
      ctx.translate(x, y)
      ctx.rotate(deg * Math.PI / 180)
      ctx.fillText(char, 0, 0)
      /**恢复旋转角度和坐标原点**/
      ctx.rotate(-deg * Math.PI / 180)
      ctx.translate(-x, -y)
    }
    runInAction(() => {
      this.login.CODE = code
    })

  }

  render() {
    const { getFieldDecorator } = this.props.form
    return (
      <div className={styles.loginPage}>
        <div id="backgroundBox" className={styles.backgroundBox}></div>
        <div className={styles.container}>
          <div className={styles.box}>
            <h3 className={styles.title}>管理员登录</h3>
            <Form className={styles.form}>
              <FormItem>
                {getFieldDecorator('username', {
                  rules: [{required: true, message: '请输入用户名'}]
                })(
                  <Input
                    className={styles.input}
                    maxLength={16}
                    placeholder='用户名'
                    onChange={ (e) => {this.login.handleInputChange(e.target.value, 'username')} }
                    addonBefore={
                      <Icon type="user" />
                  }/>
                )}
              </FormItem>
              <FormItem>
                {getFieldDecorator('password', {
                  rules: [{required: true, message: '请输入用户名'}]
                })(
                  <Input
                    className={styles.input}
                    maxLength={16}
                    type="password"
                    placeholder='密码'
                    onChange={ (e) => {this.login.handleInputChange(e.target.value, 'password')} }
                    addonBefore={
                      <Icon type="lock" />
                  }/>
                )}
              </FormItem>
              <FormItem style={{height: '53px'}}>
                {getFieldDecorator('vertifyCode', {
                  rules: [{required: true, message: '请输入密码'}]
                })(
                  <Row>
                    <Col span={15}>
                      <Input
                        className={styles.input}
                        maxLength={4}
                        placeholder='验证码'
                        addonBefore={<Icon type="safety-certificate" />}
                        onChange={ (e) => {this.login.handleInputChange(e.target.value, 'code')} }
                        />
                    </Col>
                    <Col span={9}>
                      <canvas onClick={this.createCode} width="80" height='39' ref={el => this.canvas = el}/>
                    </Col>
                  </Row>
                )}
              </FormItem>
              <div className={styles.bottom}>
                <input className={styles.loginBtn} type="submit" value='登录' onClick={() => {this.doLogin()}}/>
                <span className={styles.registerBtn} onClick={()=> {}}>注册</span>
              </div>
              <div className={styles.footer}>
                <p>欢迎登录后台管理系统</p>
              </div>
            </Form>
          </div>
        </div>
      </div>
    )
  }
}

export default LoginView